package com.zzyl.service.impl;

import cn.hutool.db.PageResult;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.ReservationDto;
import com.zzyl.entity.Reservation;
import com.zzyl.enums.BasicEnum;
import com.zzyl.enums.ReservationStatus;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.CustomerReservationMapper;
import com.zzyl.service.CustomerReservationService;
import com.zzyl.vo.CountVo;
import com.zzyl.vo.ReservationVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CustomerReservationServiceImpl implements CustomerReservationService {
    @Autowired
    CustomerReservationMapper customerReservationMapper;

    @Override
    public Integer cancelledCount(Long userId) {
        Integer count=customerReservationMapper.cancelledCount(LocalDateTime.now().withHour(0).withMinute(0).withSecond(0),LocalDateTime.now().withHour(23).withMinute(59).withSecond(59),userId);
        return count;
    }

    @Override
    public List<CountVo> countByTime(LocalDateTime time) {
        LocalDateTime endTime = time.plusHours(24);
        List<CountVo> counts=customerReservationMapper.countByTime(time,endTime);
        return counts;
    }

    @Override
    public void add(ReservationDto reservationDto) {
        Long id = reservationDto.getId();
        Integer count = cancelledCount(id);
        if(count>3){
            throw new BaseException(BasicEnum.RESERVATION_CANCEL_COUNT_UPPER_LIMIT);
        }
        Reservation reservation=new Reservation();
        BeanUtils.copyProperties(reservationDto,reservation);
        reservation.setStatus(ReservationStatus.PENDING.getOrdinal());
        reservation.setCreateBy(id);
        reservation.setCancel();
        try {
            customerReservationMapper.add(reservation);
        } catch (Exception e) {
            throw new BaseException(BasicEnum.TIME_ALREADY_RESERVATED_BY_PHONE);
        }
    }


    @Override
    public PageResponse<ReservationVo> page(Integer pageNum, Integer pageSize, Integer status) {
        PageHelper.startPage(pageNum,pageSize);
        Page<ReservationVo> pages=customerReservationMapper.page(status);
        PageResponse<ReservationVo> reservationVoPageResponse = PageResponse.of(pages, ReservationVo.class);
        return reservationVoPageResponse;
    }

    @Override
    public void cancel(Long id) {
        customerReservationMapper.cancel(id);
    }
}
